package com.ruoyi.common.core.utils;
import com.alibaba.fastjson2.JSON;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 钉钉消息发送
 */
public class DingDingPushUtil {
    public static Map<String, String> mobileMap = new HashMap<>();

    // 静态初始化块，用于在类加载时初始化Map
    static {
        // 添加信息到Map中
        mobileMap.put("李", "+86-17860780657");
        mobileMap.put("韩", "+86-19531943413");
        mobileMap.put("孙", "+86-15761388888");
        mobileMap.put("荆", "+86-15763648725");
    }

    public static void main(String[] args) {
        StringBuffer pushSb = new StringBuffer();
        pushSb.append("测试")
                .append("【")
                .append(new Date()).append("】");
        DingDingPushUtil.send(pushSb.toString());
    }

    public static String send(String content) {
        //测试机器人key
        String dingKey = "https://oapi.dingtalk.com/robot/send?access_token=e111400ce7234ef5d9afeedf2951509c1f568c7d76bd80530bde9e25115d7123";
        // 请求的JSON数据，这里我用map在工具类里转成json格式
        Map<String, Object> json = new HashMap<>();
        Map<String, Object> text = new HashMap<>();
        json.put("msgtype", "text");
        text.put("content", content);
        text.put("content1", content);
        json.put("text", text);
        // 发送post请求
        String result = DingDingPushUtil.sendPostByMap(dingKey, json);
        System.out.println("发送成功 " + result);
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, Map<String, Object> param, Map<String, String> headParam) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性 请求头
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Fiddler");
            if (headParam != null) {
                for (Map.Entry<String, String> entry : headParam.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(JSON.toJSONString(param));
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println("line=" + line);
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送POST请求，参数是Map, contentType=x-www-form-urlencoded
     *
     * @param url
     * @param mapParam
     * @return
     */
    public static String sendPostByMap(String url, Map<String, Object> mapParam) {
        Map<String, String> headParam = new HashMap<>();
        headParam.put("Content-type", "application/json;charset=UTF-8");
        return sendPost(url, mapParam, headParam);
    }

    /**
     * 甜子钉钉群 订单流程及测评
     * @param msg
     * @param userName
     * @return
     * @throws Exception
     */
    public static String sendBySginTianZai(String msg, String userName) throws Exception {
        msg = "易达:" + msg;
        String mobile = mobileMap.get(userName);
        System.out.println(mobile);
        String dingUrl = sendGetUrlBySginTianZai();
        Map<String, Object> requestJson = sendGetMsgBySgin(msg, mobile);
        String result = DingDingPushUtil.sendPostByMap(dingUrl, requestJson);
        System.out.println(result);
        return null;
    }

    /**
     * 小胖钉钉群 国际物流异常退单
     * @param msg
     * @param mobile
     * @return
     * @throws Exception
     */
    public static String sendBySginXiaoPang(String msg, String mobile) throws Exception {
        System.out.println(mobile);
        String dingUrl = sendGetUrlBySginXiaoPang();
        Map<String, Object> requestJson = sendGetMsgBySgin(msg, mobile);
        String result = DingDingPushUtil.sendPostByMap(dingUrl, requestJson);
        System.out.println(result);
        return null;
    }

    public static String sendGetUrlBySginXiaoPang() throws Exception {
        //钉钉机器人地址（配置机器人的webhook）这里我么能得到了dingUrl
        String baseUrl = "https://oapi.dingtalk.com/robot/send?access_token=";
        String token = "2f36d9a94df14e17e0d84a0f62641a9e9adc6f3c2b7c1200c5eff79626c1b44a";
        String secret = "SEC4f76fe309fa71f1d699ed2abf60b7626ebccf65214205418321e3d3b451534e3";
        long timestamp = System.currentTimeMillis();
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        String dingUrl = baseUrl + token + "&timestamp=" + timestamp + "&sign=" + URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");

        return dingUrl;
    }

    /**
     * 订单评测提醒群
     *
     * @return
     * @throws Exception
     */
    public static String sendGetUrlBySginTianZai() throws Exception {
        //钉钉机器人地址（配置机器人的webhook）这里我么能得到了dingUrl
        String baseUrl = "https://oapi.dingtalk.com/robot/send?access_token=";
        String token = "e111400ce7234ef5d9afeedf2951509c1f568c7d76bd80530bde9e25115d7123";
        String secret = "SEC4f76fe309fa71f1d699ed2abf60b7626ebccf65214205418321e3d3b451534e3";
        long timestamp = System.currentTimeMillis();
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        String dingUrl = baseUrl + token + "&timestamp=" + timestamp + "&sign=" + URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");

        return dingUrl;
    }


    public static Map<String, Object> sendGetMsgBySgin(String msg, String mobile) throws Exception {
        //是否通知所有人
        boolean isAtAll = false;

        //通知具体人的手机号码列表/可以再群里面点击个人头像进行复制
        List<String> mobileList = new ArrayList<>();
        mobileList.add(mobile);

        //发送内容在这里也可以直接 String格式作为数据
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(msg);//数据
//                .append("\n")//换行
//                .append("[对勾]");//表情
        String content = stringBuffer.toString();
        //组装数据
        //消息内容
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("content", content);

        //通知人员数据
        Map<String, Object> atMap = new HashMap<>();

        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);

        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);

        //组装数据
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("msgtype", "text");
        requestMap.put("text", contentMap);
        requestMap.put("at", atMap);

//        String requestJson = JSON.toJSONString(requestMap);

        return requestMap;
    }




}

